# -*- coding:utf-8 -*-

import os
import sys
import subprocess
import argparse

from .plugins import metaparser_factory, generator_factory
from . import ParseError, GenerateError

args = None

def parse_args():
	def directory_type(s):
		if not os.path.isdir(s):
			msg = '%s is not a dirctory.'%s
			raise argparse.ArgumentTypeError(msg)
		return s

	def exists_file_type(s):
		if not os.path.isfile(s):
			msg = '%s is not exists.'%s
			raise argparse.ArgumentTypeError(msg)
		return s

	parser = argparse.ArgumentParser(
		description = 'compile csv file(s) to programming language source code file(s).')

	parser.add_argument('--metadefine-language', dest = 'metadefine_language', default = 'xml')
	parser.add_argument('--output-language', dest = 'output_language', default = 'python')
	parser.add_argument('--include-dir',
		dest = 'include_dirs',
		type = directory_type,
		action = 'append',
		)
	parser.add_argument('--output-dir',
		dest = 'output_dir',
		type = directory_type,
		)
#	parser.add_argument('--csv-file', dest = 'csv_files', nargs='+', required = True)
	parser.add_argument('csv_files', nargs='+', type = exists_file_type)

	
	global args
	args = parser.parse_args()

def generate(csv_file):
	global args
	parser = metaparser_factory(args.metadefine_language)
	try:
		mid_result = parser.process(csv_file, args.include_dirs)
	except ParseError, e:
		sys.exit('%s\nan error occurred while parsing file(%s).'%(str(e), csv_file))
	generator = generator_factory(args.output_language)
	try:
		code = generator.process(mid_result)
	except GenerateError, e:
		sys.exit('%s\nan error occurred while generating source code.(%s).'%(str(e), csv_file))
	with open(generator.output_path(args.output_dir, csv_file), 'w') as f:
		print >>f, code
		print

def main():
	parse_args()
	global args
	for csv_file in args.csv_files:
		generate(csv_file)

